using Microsoft.AspNetCore.Mvc;
using ProcessManagementApi.DTOs;
using ProcessManagementApi.Services;
using MESData.ErrorCode;

namespace ProcessManagementApi.Controllers
{
    /// <summary>
    /// 工序管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ProcessController : ControllerBase
    {
        private readonly IProcessService _processService;

        public ProcessController(IProcessService processService)
        {
            _processService = processService;
        }

        /// <summary>
        /// 分页查询工序列表
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns>工序列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetProcesses([FromQuery] ProcessQueryDto queryDto)
        {
            var result = await _processService.GetProcessesAsync(queryDto);
            return Ok(result);
        }

        /// <summary>
        /// 根据ID获取工序详情
        /// </summary>
        /// <param name="id">工序ID</param>
        /// <returns>工序详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetProcessById(int id)
        {
            var result = await _processService.GetProcessByIdAsync(id);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 创建工序
        /// </summary>
        /// <param name="createDto">创建信息</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<IActionResult> CreateProcess([FromBody] ProcessCreateDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _processService.CreateProcessAsync(createDto);
            if (result.Code == ApiEnum.Success)
            {
                return CreatedAtAction(nameof(GetProcessById), new { id = result.Data!.Id }, result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 更新工序
        /// </summary>
        /// <param name="updateDto">更新信息</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<IActionResult> UpdateProcess([FromBody] ProcessUpdateDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _processService.UpdateProcessAsync(updateDto);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 删除工序
        /// </summary>
        /// <param name="id">工序ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProcess(int id)
        {
            var result = await _processService.DeleteProcessAsync(id);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 批量删除工序
        /// </summary>
        /// <param name="ids">工序ID列表</param>
        /// <returns>删除结果</returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDeleteProcesses([FromBody] List<int> ids)
        {
            var result = await _processService.BatchDeleteProcessesAsync(ids);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 导出工序到Excel
        /// </summary>
        /// <param name="numberOrName">工序编码/名称（模糊查询）</param>
        /// <param name="processCategoryId">工序分类ID</param>
        /// <param name="department">所属部门</param>
        /// <param name="responsiblePerson">负责人</param>
        /// <param name="isActive">状态（启用/禁用）</param>
        /// <returns>Excel文件</returns>
        [HttpGet("export")]
        public async Task<IActionResult> ExportProcesses(
            [FromQuery] string? numberOrName = null,
            [FromQuery] int? processCategoryId = null,
            [FromQuery] string? department = null,
            [FromQuery] string? responsiblePerson = null,
            [FromQuery] bool? isActive = null)
        {
            var queryDto = new ProcessExportQueryDto
            {
                NumberOrName = numberOrName,
                ProcessCategoryId = processCategoryId,
                Department = department,
                ResponsiblePerson = responsiblePerson,
                IsActive = isActive
            };

            var fileBytes = await _processService.ExportProcessesToExcelAsync(queryDto);
            var fileName = $"工序列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            
            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }

        /// <summary>
        /// 生成工序编码
        /// </summary>
        /// <returns>生成的工序编码</returns>
        [HttpGet("generate-code")]
        public async Task<IActionResult> GenerateProcessCode()
        {
            var result = await _processService.GenerateProcessCodeAsync();
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }
    }
} 